import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import './styles/login.css';
import type { loginType } from '../types/login'
import { Button, Input, Toast, Form } from 'react-vant'
import TopComponent from '../components/topComponent';
import { handleLogin } from '../utils/api'
const Login: React.FC = () => {
  const navigate = useNavigate()
  const [form] = Form.useForm();
  const [formValues, setFormValues] = useState<loginType>({ email: '', password: '' });
  const [isLoading, setIsLoading] = useState(false);
  const [showPassword, setShowPassword] = useState({
    password: false,
    confirmPassword: false
  });
  useEffect(() => {
    form.setFieldsValue(formValues);
  }, []);

  const onFinish = async () => {
    if (!formValues.email || !formValues.password) return
    try {
      setIsLoading(true)
      Toast.loading({
        message: '登录中...',
        forbidClick: true,
      })
      const params={
        email: formValues.email,
        password: formValues.password
      }
      let res = await handleLogin(params)
      console.log(res,'res');
      
      Toast.clear()
      if (res.data.code === 200) {
        Toast.success({
          message: '登录成功',
          duration: 1000,
        })
        localStorage.setItem('userInfo', JSON.stringify({ username: res.data.username, avatar: res.data.image }));
        localStorage.setItem('isLogin', "yes");
        await new Promise((resolve) => { 
          navigate('/app/shou')
         })
      }else{
        Toast.fail({
          message: res.data.mssage,
          duration: 1000,
        })
      }
    } catch (error) {
      console.log(error,'error');
      Toast.fail({
        message: '登录失败',
        duration: 1000,
      })
      
    } finally {
      setIsLoading(false)
    }


  }

  const onValuesChange = () => {
    const values = form.getFieldsValue();
    setFormValues(values);
  }
  const goBack = () => {
    navigate('/onboarding')
    console.log(123);

  }
  return (
    <>
      <div className="parentBox">
        <TopComponent title="1" handleGoBack1={goBack} />
        {/* 表单 */}
        <div className="parentBox-login">
          <Form
            form={form}
            onFinish={onFinish}
            onValuesChange={onValuesChange}
            footer={
              <div style={{ margin: '16px 16px 0' }}>
                <Button round nativeType='submit' type='primary' block
                  disabled={!formValues.email || !formValues.password}
                  loading={isLoading}
                >
                  登陆
                </Button>
              </div>
            }
          >
            <span className="parentBox-span">电子邮箱</span>
            <Form.Item
              name='email'
              rules={[{ pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, message: '请输入正确的邮箱' }]}
            >
              <Input placeholder='输入您的电子邮箱' className="parentBox-input" />
            </Form.Item>
            <span className="parentBox-span">密码</span>
            <Form.Item
              name='password'
              rules={[
                {
                  validator: (_, value) => {
                    if (/^[A-Za-z0-9_.*\/+-]{8,20}$/.test(value)) {
                      return Promise.resolve(true)
                    }
                    return Promise.reject(new Error('请输入正确的密码'))
                  },
                },
              ]}
            >
              <Input
                type={showPassword.password ? 'text' : 'password'}
                placeholder='输入您的密码'
                className="parentBox-input" />
            </Form.Item>
            <span className="form-span" onClick={() => { navigate('/register') }}>忘记密码？</span>
          </Form>
        </div>

        <div className="parentBox-divider">
          <span>或者</span>
        </div>
        <div className="third-party-login">
          <Button className="phone-btn" onClick={()=>{navigate('/phone')}}>
            <img src="/images/phone.svg" alt="phone" />
            使用手机登录
          </Button>
        </div>
        <div className="third-party-login">
          <Button className="phone-btn" onClick={()=>{navigate('/face')}}>
            <img src="/images/face.svg" alt="face" />
            人脸登录
          </Button>
        </div>
        <div className="register-link">
          <span>没有账户？</span>
          <span className="register" onClick={() => navigate('/register1')}>注册</span>
        </div>
      </div>
    </>
  );
};
export default Login;
